# -*- coding:utf-8 -*-
__author__ = 'weikai'
from login import logincic
import re
import requests
import cic_settings as SE
from parse import parseCarInfo, parsedataObjs, parseCardata, parseFee, parse_renewal_data
import  utils
from feebody import getFeebody, compare_date
from vhlPlatform import *
from calcNActualValue import calcNActualValue
from my_dbUtil.dbInsert import soupDb
from translate import getPriumeInf
from request_cic.request_getdata import vehicleList_code
from log import *
import traceback
from common import config
from request_pingan.utils import  compare_time40
from common.MqSend import send_mq,send_mq_update_carinfo
import json
log=Logger("request_cic.log")
def cic_request(requesteicc,renewal_data_dt):
    alldata={}
    headers = SE.headers
    # searchVin = data['vinNo']
    insureCarId = renewal_data_dt['insureCarId']
    CPlateNo = renewal_data_dt['plateNumber']
    searchVin = renewal_data_dt['vinNo']
    client=renewal_data_dt['client']
    isPhone=renewal_data_dt['isPhone']
    sessionId=renewal_data_dt['sessionId']
    insuranceType=renewal_data_dt["insuranceType"]
    insuranceTypeGroupId=insuranceType['insuranceTypeGroupId']
    insuranceTypeGroup=insuranceType['insuranceTypeGroup']
    endDate=renewal_data_dt.get("endDate","")
    #判断保险结束时间 如果结束时间距离今天超过40天不进行查询
    if endDate!="":
        min_time=compare_time40(endDate)
        if min_time > config.days:
            log.error("中华联合保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo,endDate))
            send_mq(client,CPlateNo,"中华联合保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo,endDate),"4","1",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
            return "中华联合保险查询在40天内的 车牌号为 %s 保险结束时间为 %s" % (CPlateNo,endDate)
        #如果当前时间小于今天
        if min_time < 0:
            endDate=utils.getlatedate(1)
    #请求车管所信息
    cardict = getCarInof(requesteicc, searchVin)
    #请求精确车型的MD5值
    md5byJy=_get_md5(requesteicc)
    #请求车辆具体信息
    carlist=_get_car_info(searchVin,md5byJy,cardict['gCNoticeType'])
    if isinstance(carlist,dict):
        pass
    else:
        log.error("%s 中华联合通过车架号以及车辆快速查询码无法车辆信息无法查询" % CPlateNo)
        send_mq(client,CPlateNo,"%s 中华联合通过车架号以及车辆快速查询码无法车辆信息无法查询" % CPlateNo,"2","4",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
    #请求车辆购置价格
    price_dict=_get_car_price(requesteicc,carlist['vehicleCode'])
    gNOfferPurChasePriceMax=price_dict['gNOfferPurChasePriceMax']
    gNOfferPurChasePriceMin=price_dict['gNOfferPurChasePriceMin']

    checkNo = cardict['checkNo']
    codestr = cardict['gCValidateCode']
    gCFstRegYm = cardict['CFstRegYm']
    gNDisplacement = cardict['gNDisplacement']
    gCPlateTyp = cardict['gCPlateTyp']
    gNNewPurchaseValue = gNOfferPurChasePriceMax  # 新车购置价
    plateNo = cardict['gCPlateNo'].encode('utf-8')
    seat = carlist['seat']
    #座位数 续保信息 与 车型搜索出的信息不一致
    seat2=renewal_data_dt.get('NSeatNum',999)
    if seat2!=999 and seat!=seat2:
        seat=seat2

    if int(seat) <= 6:
        SY_seatcode = '302001001'
        JQ_seatcode = '302001001'
    elif int(seat) > 6 and int(seat) < 10:
        SY_seatcode = '302001008'
        JQ_seatcode = '302001022'
    elif int(seat) >= 10:
        SY_seatcode = '302001016'
        JQ_seatcode = '302001022'
    else:
        SY_seatcode = '302001001'
        JQ_seatcode = '302001001'
    gNDiscussActualValue = calcNActualValue(gCFstRegYm, gNNewPurchaseValue, SY_seatcode)
    gNDiscussActualValue = str(float(gNDiscussActualValue))
     # 协商实际价值
    feedict = {"gNNewPurchaseTaxValue": carlist['purchasePriceTax'],  # 新车购置价
               "gNKindredPrice": carlist['kindredPrice'],
               "gNKindredPriceTax": carlist['kindredPriceTax'],
               "gNNewPurchaseValue": carlist['purchasePrice'],
               "gNDiscussActualValue": gNDiscussActualValue,
               "gCFrmNo": carlist['hvinRoot'],
               "gCMonDespRate": "307007002",  # 月折旧率
               "gNActualValue": gNDiscussActualValue,
               "gNOfferPurChasePriceMax": gNOfferPurChasePriceMax,
               "gNOfferPurChasePriceMin": gNOfferPurChasePriceMin,
               "gCIndustryModelCode": carlist['hyVehicleCode'],
               "gCIndustryModelName": carlist['hyVehicleName'],  # 要转码
               "gCNoticeType": carlist['vehicleFgwCode'],
               "gCProdPlace": carlist['importF'].encode("utf-8"),  # 中文需要转为012
               "gCFamilyCode": carlist['familyCode'],
               "gCFamilyName": carlist['familyName'].encode("utf-8"),
               "gCFstRegYm": gCFstRegYm,
               "gCModelNme": carlist['vehicleName'].encode("utf-8"),
               "gCBrandId": carlist['brandName'].encode("utf-8"),
               "gCModelCde": carlist['vehicleCode'],
               "gCSearchCode": checkNo,
               "gCValidateCode": codestr,
               "gCPlateNo": plateNo,
               "gCEngNo": cardict['CEngNo'],
               "gNDisplacement": str(float(carlist['displacement']) / 1000),
               "gCPlateTyp": cardict['gCPlateTyp'],
               "gCCarAge": "306002",  # age
               "gNSeatNum": seat,
               "gNPoWeight": cardict['NCurbWt'],
               "RVehlcleTonnage":cardict.get("RVehlcleTonnage","0"),
               "lNVhlActVal": gNDiscussActualValue,
               "lNDeductible_036001": "2000",
               "lNVhlActVal_036005": gNDiscussActualValue,
               "lNVhlActVal_036007": gNDiscussActualValue,
               "gCRegVhlTyp": cardict['gCRegVhlTyp'],
               "NCurbWt": cardict['NCurbWt'],
               "hCAppNme": cardict['hCAppNme'].encode("utf-8"),
               "jCGender": "1061",
               "jCOwnerAge": "341060",
               "JQgCVhlTyp": JQ_seatcode,  # 车辆类型代码
               "SYgCVhlTyp": SY_seatcode,  # 车辆类型代码
               "endDate": endDate,  # 上期保险结束时间
               "insuranceType":insuranceType #保险类型
               }
####################################计算费用###############################################
    fee_url = 'http://carply.cic.cn/pcis/policy/universal/quickapp/actionservice.ai'
    d = getFeebody(feedict)
    feedata = 'ADAPTER_TYPE=JSON_TYPE&SERVICE_TYPE=ACTION_SERVIC&CODE_TYPE=CODE_TYPE&BEAN_HANDLE=baseAction&ACTION_HANDLE=perform&SERVICE_NAME=offerBizAction&SERVICE_MOTHOD=calcPremium&DW_DATA=' + d + '&HELPCONTROLMETHOD=common&SCENE=UNDEFINED&BIZ_SYNCH_CONTINUE=false&CUST_DATA=contiOfferMrk%253D1%2523%2523%2523multiOfferFlagMrk%253D1'
    feeresp = requesteicc.post(url=fee_url, data=feedata, headers=headers)
    feeresp = feeresp.json()
    if endDate=="":
        renewal_data_dt['endDate']=utils.getlatedate(1)
    datestr = compare_date(renewal_data_dt['endDate'], utils.getlatedate(0))
    SY_fTInsrncBgnTm = utils.getlatedate(1, datestr) + ' 00:00:00'  # 保险起止期(商)
    SY_fTInsrncEndTm = utils.getlatedate(365, datestr) + " 23:59:59"  # 保险起止期(商)

    if "终保日期" in feeresp['RESULT_MSG'] and "起保日期" in feeresp['RESULT_MSG'] :
        str1="\d{4}-\d{2}-\d{2}"
        datelist=re.findall(str1,feeresp['RESULT_MSG'],re.S)
        if len(datelist)==2:
            bigdate=compare_date(datelist[0],datelist[1])
            bigdate=compare_date(bigdate,utils.getlatedate(0))
            feedict['endDate']=bigdate
            d=getFeebody(feedict)
            feedata='ADAPTER_TYPE=JSON_TYPE&SERVICE_TYPE=ACTION_SERVIC&CODE_TYPE=CODE_TYPE&BEAN_HANDLE=baseAction&ACTION_HANDLE=perform&SERVICE_NAME=offerBizAction&SERVICE_MOTHOD=calcPremium&DW_DATA='+d+'&HELPCONTROLMETHOD=common&SCENE=UNDEFINED&BIZ_SYNCH_CONTINUE=false&CUST_DATA=contiOfferMrk%253D1%2523%2523%2523multiOfferFlagMrk%253D1'
            feeresp=requesteicc.post(url=fee_url,data=feedata,headers=headers)
            feeresp=feeresp.json()

    if len(feeresp['WEB_DATA']) > 0:
        feedt = parseFee(feeresp)
        lstrs = getPriumeInf(feedt, seat)
        #data=[开始时间,结束时间，座位数，组合id (insureTypeGroupId )，车辆id，公司id]
        soupDb(lstrs, [SY_fTInsrncBgnTm, SY_fTInsrncEndTm, seat,insuranceTypeGroupId,insureCarId,"4"])
        log.info(u"中华联 合入库成功:%s|%s" % (plateNo, searchVin))

        send_mq(client,plateNo,"","1","4",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
    if len(feeresp['WEB_DATA']) <= 0:
        log.error(u"中华联合 车架号：%s,错误信息%s:" % (searchVin, feeresp['RESULT_MSG'].replace("\n", "")))
        #返回错误信息
        msg=feeresp['RESULT_MSG'].replace("\n","")
        send_mq(client,plateNo,msg,"2","4",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
        return msg



def _get_md5(requesteicc):
    #获取查询车辆精确信息的MD5
    res3 = requesteicc.get(
        url='http://carply.cic.cn/pcis/policy/universal/quickapp/quick_offer.jsp?isOffer=1&prodNo=0360&dptCde=32010101&CUnionMrk=0')
    res_body = res3.text
    if res3.status_code == 200:
        md5byJy = re.findall(r"md5byJy = \"(.+?)\";", res_body, re.S)[0]
        return md5byJy
    else:
        res_body = requesteicc.get(
            url='http://carply.cic.cn/pcis/policy/universal/quickapp/quick_offer.jsp?isOffer=1&prodNo=0360&dptCde=32010101&CUnionMrk=0')
        res_body = res3.text
        md5byJy = re.findall(r"md5byJy = \"(.+?)\";", res_body, re.S)[0]
        return md5byJy

def _get_car_info(searchVin,md5byJy,gCNoticeType):
    '''
    :param searchVin: 车架号
    :param md5byJy: MD5唯一值
    :param gCNoticeType: 车辆型号
    :return:
    '''
    ######################请求车辆信息##################################
    request114 = requests.session();
    headers114 = SE.headers
    request114.headers.update(headers114)
    # 车架号
    # searchVin='LMVHEKFD6EA029484'
    # searchVin='LFV2A11K8F4192886'
    validNo = md5byJy
    # vehicleId='I0000000000000000230000000000033'
    search_url = 'http://114.251.1.161/zccx/search?regionCode=00000000&jyFlag=0&businessNature=A&operatorCode=0000000000&returnUrl=http://carply.cic.cn/pcis/offerAcceptResult&vname=&searchVin=' + searchVin + '&vinflag=1&validNo=' + validNo
    repon114 = request114.get(url=search_url)
    if "没有找到符合条件的数据" in repon114.text:
        #log.error("%s 通过车架号未查询到车辆信息 %s" % (CPlateNo,searchVin) )
        carlist=vehicleList_code(request114,gCNoticeType)
    else:
        carlist = parseCarInfo(repon114.text)
    if len(carlist)!=0:
        gCSearchCode = vehicleId = carlist[len(carlist)-1]['vehicleId']
        vehicleCode = carlist[len(carlist)-1]['vehicleCode']
        ######################选择车辆##################################
        getVehicleForReturn_url = 'http://114.251.1.161/zccx/getVehicleForReturn.shtml?vehicleCode=' + vehicleId + '&vehicleId=' + vehicleId + '&hvinRoot=' + searchVin + '&hvinFlag=1'
        getVehicleForReturnrsp = request114.post(url=getVehicleForReturn_url)
        # log.info(getVehicleForReturnrsp.text)
        dt = parseCardata(getVehicleForReturnrsp.text)
        dt['vehicleCode']=vehicleCode
        return dt
    else:
        #log.error("%s 中华联合通过车架号以及车辆快速查询码无法车辆信息无法查询" % CPlateNo)
        #send_mq(client,CPlateNo,"%s 中华联合通过车架号以及车辆快速查询码无法车辆信息无法查询" % CPlateNo,"2","4",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
        return "中华联合通过车架号以及车辆快速查询码无法车辆信息无法查询"

def _get_car_price(requesteicc,vehicleCode):
    try:
        #####################新车购置浮动上线###############
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        ModeCode = vehicleCode.replace(' ', '').replace(u'\r', '').replace(u'\n', '')
        getOfferPrice_url = 'http://carply.cic.cn/pcis/policy/universal/quickapp/actionservice.ai'
        getOfferPricedata = 'ADAPTER_TYPE=JSON_TYPE&SERVICE_TYPE=ACTION_SERVIC&CODE_TYPE=CODE_TYPE&BEAN_HANDLE=baseAction&ACTION_HANDLE=perform&SERVICE_NAME=offerDataLoadAction&SERVICE_MOTHOD=getOfferPrice&DW_DATA=%255B%255D&HELPCONTROLMETHOD=common&SCENE=UNDEFINED&BIZ_SYNCH_CONTINUE=false&CUST_DATA=dptCde%253D32010101%2523%2523%2523prodNo%253D0360_0332%2523%2523%2523modelCde%253D' + ModeCode
        getOfferPriceresp = requesteicc.post(url=getOfferPrice_url, data=getOfferPricedata, headers=headers)
        getOfferPriceresp = getOfferPriceresp.json()
        gNOfferPurChasePriceMax = getOfferPriceresp['JSON_OBJ']['maxPrice']  # 新车购置价浮动上限
        gNOfferPurChasePriceMin = getOfferPriceresp['JSON_OBJ']['minPrice']  # 新车购置价浮动下
        return {"gNOfferPurChasePriceMax":gNOfferPurChasePriceMax,"gNOfferPurChasePriceMin":gNOfferPurChasePriceMin}
    except Exception,e:
        log.error(e)
        return 0

